<?php

namespace App\Http\Controllers\Exm;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\Eloquent\Exm\WarehouseRepository as Warehouse;
use App\Repositories\Eloquent\Exm\QuestionRepository as Question;
use App\Repositories\Eloquent\Exm\RecruitRepository as Recruit;

/**
 * Class LoginController
 * @package App\Http\Backend\Controllers
 */
class WarehouseController extends Controller
{
    /**
     * @var Administrator
     */
    protected $warehouse, $question;

    protected $recruit;

    public function __construct(Warehouse $warehouse,Question $question, Recruit $recruit)
    {
        parent::__construct();

        $this->warehouse = $warehouse;

        $this->question = $question;

        $this->recruit = $recruit;
    }


    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $warehouses = $this->warehouse->index()->paginate(60);

        return view($this->view, compact('warehouses'));
    }


    public function create()
    {
        return view($this->view);
    }


    public function store(Request $request)
    {
        return $this->warehouse->store($request);
    }


    public function edit($id)
    {
        $warehouse = $this->warehouse->show($id);

        if ($warehouse instanceof JsonResponse && $warehouse->getStatusCode() === 404) {
            return abort('404');
        }

        return view($this->view, compact('warehouse'));
    }


    public function update(Request $request, $id)
    {
        return $this->warehouse->renew($request, $id);
    }


    public function item($id)
    {
        $warehouse = $this->warehouse->show($id);

        if ($warehouse instanceof JsonResponse && $warehouse->getStatusCode() === 404) {
            return abort('404');
        }

        $questions = $this->question->index()->with('options')->where('type', $warehouse->type)->get();

        foreach($questions as $question){
            $question->selected = false;
            foreach($warehouse->items as $item){
                if($item->warehouse_id == $warehouse->id && $item->question_id == $question->id)
                    $question->selected = true;
            }
        }

        $questions = $questions->sortBy('id');//->sortByDesc('selected');

        return view($this->view, compact('warehouse','questions'));
    }


    public function select(Request $request, $id)
    {
        return $this->warehouse->setItems($request, $id);
    }


    public function recruit(Request $request)
    {
        $recruits = $this->recruit->index($request);

        return view($this->view, compact('recruits'));
    }
}
